package com.lantogis.gradient

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View


/**
 * VerticalLinearGradientView
 *Created by zxn on 2021/4/15.vertical
 **/
class VerticalLinearGradientView : View {

    companion object {

    }

    //默认渐变色开始颜色(红色)
    private val DEFAULT_START_COLOR: Int = Color.parseColor("#FF0000")
    private val DEFAULT_END_COLOR = Color.parseColor("#FFFF00")

    //开始、结束颜色
    private val mStartColor = DEFAULT_START_COLOR
    private val mEndColor = DEFAULT_END_COLOR

    //绘制的矩形区域
    private val mRectF: RectF by lazy {
        RectF()
    }

    //画笔
    private val mPaint: Paint by lazy {
        Paint().apply {
            isAntiAlias = true
            style = Paint.Style.FILL
        }
    }

    constructor(context: Context) : this(context, null, 0)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mRectF.left = 0F
        mRectF.top = 0F
        mRectF.right = width.toFloat()
        mRectF.bottom = height.toFloat()
        //上到下设置渐变色
        mPaint.shader =
            LinearGradient(0f, 0f, 0f, mRectF.bottom, mStartColor, mEndColor, Shader.TileMode.MIRROR)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(mRectF, mPaint)
    }


}